 
# -*- coding: iso-8859-15 -*-
import sys
import sqlite3
import os
import csv
import hashlib
import uuid
from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('config.ini')

currver = parser.get('Config','currver')
database = parser.get('Config','database')
VAR_Err = parser.get('Config','VAR_Err')
VAR_Deb = parser.get('Config','VAR_Deb')
debug = parser.get('Config','debug')
totals = parser.get('Config','totals')


if debug == "1":
    print VAR_Deb + "---------------------------------------------"
    print VAR_Deb + "Config file Loaded"
    print VAR_Deb + "Debug mode ON"
    print VAR_Deb + "---------------------------------------------"

def quitter():
    quit()

def deleter(hash):
    hash = replace(str(hash))
    conn = sqlite3.connect(database)
    c = conn.cursor()
    c.execute("DELETE FROM vulnerabilities WHERE MD5 = '"+hash+"'")
    c.execute("DELETE FROM imported WHERE MD5 = '"+hash+"'")
    conn.commit()
    conn.close()
    print "Deletion Done!"
    quit()
    
def md5(filename):
    if debug == "1":
        print VAR_Deb + "MD5 Function Started"
    m = hashlib.md5()
    try:
        fd = open(filename,"rb")
    except IOError:
        print VAR_Err + "File", filename, "can't be opened!"
        quiter()
    content = fd.readlines()
    fd.close
    for eachLine in content:
        m.update(eachLine)
    return m.hexdigest()

def ODB():
    if debug == "1":
        print VAR_Deb + "Open DB GO"
    print "Opening Database"
    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute("SELECT * FROM Version")
    except:
        if debug == "1":
            print VAR_Deb + "Version not found"
        print VAR_Err + "Database is out of date, updating!"
        c.execute('''CREATE TABLE Version(VersionID int)''')
        c.execute('''INSERT INTO Version VALUES ("0.1")''')
        conn.commit()
        print "Updated to version " + currver
        c.execute("SELECT * FROM Version")
        conn.commit()
    if debug == "1":
        print VAR_Deb + "DB Opened"
    version = c.fetchone()
    if version < currver:
        print "READ"
        print VAR_Err + "Database is out of date, updating!"
        print "Updated to version " + currver
        quit()
    c.close
    ExistanceCheck()

def ExistanceCheck():
    if debug == "1":
        print VAR_Deb + "MD5 Uniqueness check"
    conn = sqlite3.connect(database)
    c = conn.cursor()
    tstquery = c.execute("SELECT * FROM Imported WHERE MD5='"+MD5F+"'")
    try:
        tstqueryoutput = tstquery.fetchone()[0].strip()
    except:
        if debug == "1":
            print VAR_Deb + "MD5 Exists"
        print VAR_Err + "Report already loaded into database\nPlease use the remove (-rm) option with the following hash:\n-----\n"+str(MD5F)+"\n-----\nThis will remove all entries from that report!"
        quitter()
    if debug == "1":
        print VAR_Deb + "MD5 New"
    else:
        print "Adding Hash " + MD5F + " to the database for import"
        c.execute("INSERT INTO Imported VALUES('"+MD5F+"')")    
        conn.commit()

def MKDB():
    if debug == "1":
        print VAR_Deb + "Create Database"
    
    conn=sqlite3.connect(database)
    c = conn.cursor()
    c.execute('''CREATE TABLE Vulnerabilities(PluginID int, CVE text, CVSS text, Risk text, Host text, Protocol text, Port text, Name text, MD5 text)''')
    c.execute('''CREATE TABLE Imported(MD5 text)''')
    c.execute('''CREATE TABLE Version(UID int,VersionID int)''')
    c.execute('''INSERT INTO Version VALUES ("1","0.1")''')
    conn.commit()
    c.close
    print "Created!"
    ODB()

def opmak():    
    if os.path.isfile(database):
        print "checking if database exists:"
        ODB()
    else:
        print "Database doesn't exist yet, creating"
        MKDB()

def replace(name):
    f = name.replace('\'','')
    f = f.replace('[','')
    f = f.replace(']','')
    return f

def information():
    print "call the script using the following syntax:"
    print ""

f = str(sys.argv[1])
if f == "-rm":
    print "\033[93mremove mode\033[0m"
    hash = sys.argv[2:]
    print "removing all entries containing \033[91m" + replace(str(hash)) + "\033[0m"
    deleter(hash)
else:
    information()
MD5F = md5(replace(f))

if debug == "1":
    print VAR_Deb + "Generated MD5: "+MD5F

opmak()

spamreader = csv.reader(open('nessus.csv', 'rU'), delimiter=',', quotechar='"')
csv.field_size_limit(100000000)
i=0
low=0
none=0
medium=0
high=0
critical=0
spamreader.next()
conn = sqlite3.connect(database)
c = conn.cursor()

print "\033[92mImporting data, please wait!\033[0m"
for row in spamreader:
    if row[3] == 'Low':
        low=low + 1
        continue
    elif row[3] == "None":
        none=none+1
        continue
    elif row[3] == "Medium":
        medium=medium+1
        continue
    elif row[3] =="High":
        high=high+1
    elif row[3] =="Critical":
        critical=critical+1
    VAR_Replace = row[7]
    VAR_Replace = VAR_Replace.replace('\'','')

    print row[8]
    
    i=i+1
    if debug == "1":
        if i == 1:
            print VAR_Deb + "Skipping DB Entries"
    else:
        c.execute("INSERT INTO Vulnerabilities VALUES ("+ row[0] + ",'" + row[1] +"','"+row[2]+"','"+row[3]+"','"+row[4]+"','"+row[5]+"','"+row[6]+"','"+VAR_Replace+"','"+MD5F+"')")

    try:    
        conn.commit()
    except:
        print "Database is possibly open or damaged, please check"
        quit()

if debug == "1":
    print VAR_Deb + "Nothing imported due to debug"
    print VAR_Deb + "---------------------------------------------"
else:
    print "Amount:" + str(i) +" Imported!"
    
if totals == "1":
    print "Critical:"+str(critical)
    print "High:"+str(high)
    print "Medium:"+str(medium)
    print "Low:"+str(low)
    print "None:"+str(none)
c.close()
